package com.ruoyi.web.controller.tlc.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.TlcUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.UserFaceRandomGenerator;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.tlc.TlcFaq;
import com.ruoyi.system.service.tlc.ITlcFaqService;
import com.ruoyi.system.service.tlc.ITlcUserService;
import com.ruoyi.web.config.WxMaProperties;
import com.ruoyi.web.controller.common.CommonController;
import com.ruoyi.web.vo.WxLoginCode;
import com.ruoyi.web.vo.WxLoginResult;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 参数配置 信息操作处理
 * 
 * @author ruoyi
 */
@Slf4j
@RestController
@RequestMapping("/apilogin")
public class LoginController extends BaseController
{

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private WxMaProperties wxMaProperties;

    @Autowired
    private ITlcUserService tlcUserService;

    @PostMapping("")
    public AjaxResult apilogin(@RequestBody WxLoginCode loginCode)
    {
        log.info(JSON.toJSONString(loginCode));
        if (StringUtils.isBlank(loginCode.getCode())) {
            return AjaxResult.error("登陆失败!");
        }
        if (!wxMaService.switchover(wxMaProperties.getCurrAppId())) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", wxMaProperties.getCurrAppId()));
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(loginCode.getCode());
            String sessionKey = session.getSessionKey();
            String openId = session.getOpenid();
            //通过openid去获取用户 没有用户就创建用户  完事儿调用登陆
            LambdaQueryWrapper<TlcUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TlcUser::getOpenId,openId);
            TlcUser user = null;
            try {
                user = tlcUserService.getOne(wrapper);
            }catch (Exception e){
                user = null;
            }
            if(user==null){
                //新建个用户
                WxMaUserInfo wxMaUserInfo = wxMaService.getUserService().getUserInfo(sessionKey,loginCode.getUserInfo().getEncryptedData(), loginCode.getUserInfo().getIv());
                log.info("wxMaUserInfo:{}", JSON.toJSONString(wxMaUserInfo));
                user = new TlcUser();
                //01-69  https://img.qytrades.com/min/images/user_face/user_face_69.png
//                user.setHeadPic(wxMaUserInfo.getAvatarUrl());
                user.setHeadPic(String.format("https://img.qytrades.com/min/images/user_face/user_face_%s.png", UserFaceRandomGenerator.generateFormattedRandomNumber()));
                user.setNickname(wxMaUserInfo.getNickName());
                user.setBalance("0");
                user.setAssistantCoin("0");
                user.setOpenId(openId);
                user.setStatus("1");
                user.setCreateTime(new Date());
                tlcUserService.save(user);
            }
            // 生成令牌
            String token = loginService.loginXcx(openId);
            WxLoginResult.UserInfo resUserInfo = new WxLoginResult.UserInfo();
            resUserInfo.setUserName(user.getNickname());
            resUserInfo.setId(user.getId().toString());
            resUserInfo.setAvatar(user.getHeadPic());
            WxLoginResult wlr = new WxLoginResult();
            wlr.setToken(token);
            wlr.setUserInfo(resUserInfo);
            return AjaxResult.success(wlr);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error("登陆失败!");
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }

    }

}
